import BasePanel from "./BasePanel";
import { DialogData } from "../Data/DialogData";
import TypeWriterEffect from "../Tools/UiTool/TypeWriterEffect";
import { utils } from "../../utils/CommonUtil";
import EnumData from "../../Enum/EnumData";

export default class DialogPanel extends Laya.Script {
    private m_fui: fairygui.GComponent;

    /** 打字机*/
    private typeWrite: TypeWriterEffect;
    /** 打字机所在位置 当背景角色在左边的时候*/
    private leftPosX: number;
    /** 打字机所在位置 当背景角色在右边的时候*/
    private rightPosX: number;
    /** 对话背景图*/
    private dialogBg: fairygui.GLoader;
    /** 当前正在打的对话数据*/
    private curTypeData: Array<DialogData> = new Array<DialogData>();

    private dialogText: fairygui.GLabel;

    private dialogGroup: fairygui.GGroup;

    public SetData(m_fui: fairygui.GComponent) {
        this.m_fui = m_fui;
        this.initFui();
    }

    private initFui() {
        this.dialogText = this.m_fui.getChild("dialogText").asLabel;

        this.typeWrite = utils.CommonUtils.CustomAddComponent(this.dialogText.displayObject, TypeWriterEffect);
        this.typeWrite.SetData(this.dialogText);
        this.dialogBg = this.m_fui.getChild("dialogBg").asLoader;
        this.m_fui.getChild("bgTouch").onClick(this, this.OnClickText);

        this.leftPosX = this.m_fui.getChild("leftPos").asImage.x;
        this.rightPosX = this.m_fui.getChild("rightPos").asImage.x;
        this.dialogGroup = this.m_fui.getChild("dialogPanel").asGroup;
    }

    public StartType(dialogDatas: Array<DialogData>) {
        this.dialogGroup.visible = true;

        this.curTypeData = dialogDatas;
        this.TypeCurStrKey();   
    }

    /** 打当前的字*/
    private TypeCurStrKey() {
        if (this.curTypeData.length > 0) {
            let data: DialogData = this.curTypeData[0];
            /** 需要玩家名字*/

            this.typeWrite.StartType(window.gameFacade.ConfigMng.GetLanguageByKey(data.languageKey));

            window.gameFacade.AtlasMng.SetSpriteByName(this.dialogBg, "GameUIPanel", data.spriteName);

            /** 根据背景人的位置 设置文字的位置*/
            if (data.isBgRight) {
                this.dialogText.setXY( this.leftPosX,this.dialogText.y);
            }
            else {
                this.dialogText.setXY( this.rightPosX,this.dialogText.y);
            }
            this.curTypeData.shift();
        }
        else {
            this.dialogGroup.visible = false;
        }
    }

    /** 点击ui 如果还没打完 就直接打完 如果打完了 就显示打下一段 如果下一段没了 就关闭*/
    private OnClickText() {
        console.log("OnClickText!!!!!");
        /** 如果正在打 就停止打*/
        if (this.typeWrite.IsTyping()) {
            this.typeWrite.EndType();
        }
        else {
            /** 如果还有没打的 就打下一句*/
            if (this.curTypeData.length > 0) {
                this.TypeCurStrKey();
            }
            /** 全打完了 直接隐藏*/
            else {
                this.dialogGroup.visible = false;
            }
        }
    }
}